﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CluelessGame
{
    public class ErrorLog
    {
        public delegate void LogErrorDelegate(string message);
        public event LogErrorDelegate ExternalLogError;

        TextWriter textWriter = null;

        public ErrorLog()
        {

        }

        public void Initialize(string outputFilePath)
        {
            try
            {
                if (File.Exists(outputFilePath))
                {
                    int backupNumber = 0;
                    string targetBackupName = outputFilePath + backupNumber;

                    while (File.Exists(targetBackupName))
                    {
                        backupNumber++;
                        targetBackupName = outputFilePath + backupNumber;
                    }

                    File.Move(outputFilePath, targetBackupName);
                }

                textWriter = File.CreateText(outputFilePath);
            }
            catch (IOException e)
            {
                System.Windows.MessageBox.Show("Could not start error log utility. " + e.Message);
                textWriter = null;
            }
   
        }

        public void LogError(string message)
        {
            if (textWriter != null)
            {
                textWriter.WriteLine(String.Format("{0}: {1}", DateTime.Now, message));
            }

            if (ExternalLogError != null)
            {
                ExternalLogError(message);
            }
        }

        public void Terminate()
        {
            if (textWriter != null)
            {
                textWriter.Close();
                textWriter = null;
            }
        }

        public void ClearMemoryLog()
        {

        }

    }
}
